package com.data.collect.logic;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.NfcAdapter;
import android.provider.Settings;
import android.util.Log;

import com.data.collect.tool.ListUtil;
import com.data.collect.tool.Logger;
import com.data.collect.tool.MD5Util;
import com.data.collect.tool.RootTool;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by wanggenlin on 17-6-6.
 */
public class DeviceController {


    private static DeviceController instance;

    public static DeviceController getInstance() {
        if (instance == null){
            instance = new DeviceController();
        }
        return instance;
    }
    Context context;
    public void init(Context context){
        this.context = context;
    }

    /**
     * 陀螺信息
     * @return JSON 信息　n 名称　ｔ类型　ｖ 版本
     */
    public String getSensorInfor(){
        SensorManager  sensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
        List<Sensor> list =  sensorManager.getSensorList(Sensor.TYPE_ALL);
        JSONArray ja = new JSONArray();
        for (Sensor s:list){
            try {
                JSONObject js = new JSONObject();
                js.put("n",s.getName());
                js.put("t",s.getType());
                js.put("v",s.getVersion());
                ja.put(js);
            }catch (Exception e){

            }
        }
        if (ListUtil.isNullOrEmpty(list)){
            return "";
        }
        return ja.toString();
    }

    public String blueInfor(){
        BluetoothAdapter mAdapter= BluetoothAdapter.getDefaultAdapter();
        String address = mAdapter.getAddress();
        String name = mAdapter.getName();
        int  state = mAdapter.getState();
        boolean  enabled = mAdapter.isEnabled();
        Set<BluetoothDevice> set= mAdapter.getBondedDevices();
        JSONObject js = new JSONObject();
        try {
            js.put("adr",address);
            js.put("n",name);
            js.put("s",state);
            js.put("e",enabled);
            JSONArray ja = new JSONArray();
            Iterator<BluetoothDevice> it = set.iterator();
            while (it.hasNext()) {
                BluetoothDevice str = it.next();
                JSONObject jo = new JSONObject();
                jo.put("n",str.getName());
                jo.put("adr",str.getAddress());
                jo.put("t",str.getType());
                jo.put("s",str.getBondState());
                js.put("ds",ja);
            }

        }catch (Exception  e){
            Logger.e(e.getLocalizedMessage(),e);
        }
        return js.toString();
    }


    public String wifiInfor(){
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("e",wifiManager.isWifiEnabled());
            if (wifiManager.isWifiEnabled()){
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                String ip = intToIp(ipAddress);
                jsonObject.put("ip",ip);
                jsonObject.put("bssid",wifiInfo.getBSSID());
                jsonObject.put("Hbssid",wifiInfo.getHiddenSSID());
                jsonObject.put("lspeed",wifiInfo.getLinkSpeed());
                jsonObject.put("ssid",wifiInfo.getSSID());
                jsonObject.put("mac",wifiInfo.getMacAddress());
                if (wifiInfo.getMacAddress().equals("02:00:00:00:00:00")){
                    jsonObject.put("mac",getMac6());
                }
                jsonObject.put("rssi",wifiInfo.getRssi());
            }
        }catch (Exception e){
        }
        return jsonObject.toString();
    }
    public String wifiList(){
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        JSONArray ja = new JSONArray();
        List<ScanResult> results =  wifiManager.getScanResults();
        for (ScanResult s:results){

            try {
                JSONObject js = new JSONObject();
                js.put("bssid",s.BSSID);
                js.put("cwidth",s.channelWidth);
                js.put("name",s.operatorFriendlyName.toString());
                js.put("dc",s.describeContents());
                js.put("pasNetwork",s.isPasspointNetwork());
                js.put("venueName",s.venueName.toString());
                js.put("level",s.level);
                js.put("timestamp",s.timestamp);
                ja.put(js);
            }catch (Exception e){

            }
        }
        return ja.toString();

    }


    public String voiceSystem(){
        JSONObject js  = new JSONObject();
        try {

            AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

//通话音量

            int max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_VOICE_CALL );
            int current = mAudioManager.getStreamVolume( AudioManager.STREAM_VOICE_CALL );
            js.put("callM",max);
            js.put("callC",current);

//系统音量

            max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_SYSTEM );
            current = mAudioManager.getStreamVolume( AudioManager.STREAM_SYSTEM );
            js.put("streamM",max);
            js.put("streamC",current);

//铃声音量

            max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_RING );
            current = mAudioManager.getStreamVolume( AudioManager.STREAM_RING );
            js.put("streamRM",max);
            js.put("streamRC",current);

//音乐音量

            max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
            current = mAudioManager.getStreamVolume( AudioManager.STREAM_MUSIC );
            js.put("streamMM",max);
            js.put("streamMC",current);

//提示声音音量

            max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_ALARM );
            current = mAudioManager.getStreamVolume( AudioManager.STREAM_ALARM );
            js.put("alarmM",max);
            js.put("alarmC",current);
        }catch (Exception e){

        }
        return js.toString();

    }




    private String intToIp(int i) {

        return (i & 0xFF ) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF) + "." +
                ( i >> 24 & 0xFF) ;
    }

    /**
     * 获取手机的MAC地址
     * @return
     */
    public String getMac6(){
        String str="";
        String macSerial="";
        try {
            Process pp = Runtime.getRuntime().exec(
                    "cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);

            for (; null != str;) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address")
                        .toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();

            }

        }
        return macSerial;
    }
    private static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }
    private static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

     public int getSystemBrightness() {
               int systemBrightness = 0;
                try {
                      systemBrightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
                } catch (Settings.SettingNotFoundException e) {
                   e.printStackTrace();
          }
                return systemBrightness;
        }

    public boolean isRoot() {
        return RootTool.isRootSystem();
    }

    public String  installAppList(){
        PackageManager packageManager =context.getPackageManager();
        List<PackageInfo> list = packageManager.getInstalledPackages(0);
        JSONArray ja = new JSONArray();
        for (PackageInfo info:list){
            ja.put(MD5Util.Bit16(info.packageName));
        }
        return ja.toString();
    }
    public boolean isSupportNFC() {
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(context);
        return nfcAdapter==null;
    }





    @Override
    public String toString() {
        return
                "\n SensorInfor="+getSensorInfor()+
                "\n blueInfor="+blueInfor()+
                "\n wifi="+wifiInfor()+
                "\n wifiList="+wifiList()+
                "\n voice="+voiceSystem()+
                "\n bright="+getSystemBrightness()+
                "\n root="+isRoot()+
//                "\n appList="+installAppList()+
                "\n nfc="+isSupportNFC()+


                "";
    }
}
